<template>
  <div class="container">
    <el-card class="table-container">
      <div style="margin: 0 10px 20px 10px">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="评测人" prop="name" placeholder="请选择评测人">
            <el-col :span="22">
              <el-select v-model="searchForm.userId">
                <el-option v-for="item in users" :key="item.id" :label="item.realName" :value="item.id" />
              </el-select>

            </el-col>
          </el-form-item>
          <el-form-item label="选择月份" prop="month" placeholder="请选择月份">
            <el-col :span="22">
              <el-date-picker v-model="searchForm.month" value-format="yyyy-MM" type="month" placeholder="选择月">
              </el-date-picker>
            </el-col>
          </el-form-item>



          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item> -->
          <el-form-item>
            <el-button :loading="exportLoading" type="success" plain @click="handleExportExcel">Excel导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="tableData.list" :header-row-class-name="'table-head-th'" row-key="id" fit
        v-loading="queryLoading" highlight-current-row>
        <el-table-column width="100" align="center" key="name" show-overflow-tooltip prop="name" label="评测人" />
        <el-table-column width="140" align="center" key="createTime" show-overflow-tooltip prop="createTime"
          label="评测时间" />
        <el-table-column width="100" align="center" v-for="target in DepartmentList" :key="target.name"
          show-overflow-tooltip :prop="`Department${target.id}`" :label="target.name">
          <template slot-scope="scope">

            <el-tag v-if="scope.row[`Department${target.id}`] == 'A'">A</el-tag>
            <el-tag v-if="scope.row[`Department${target.id}`] == 'B'" type="success">B</el-tag>
            <el-tag v-if="scope.row[`Department${target.id}`] == 'C'" type="info">C</el-tag>
            <el-popover placement="top" trigger="hover" :content="scope.row[`ReasonD${target.id}`]">
              <el-tag v-if="scope.row[`Department${target.id}`] == 'D'" slot="reference" type="warning">D</el-tag>
            </el-popover>
            <el-popover placement="top" trigger="hover" :content="scope.row[`ReasonD${target.id}`]">
              <el-tag v-if="scope.row[`Department${target.id}`] == 'E'" slot="reference" type="danger">E</el-tag>
            </el-popover>


          </template>

        </el-table-column>
        <el-table-column width="100" align="center" v-for="target in EmployeesList" :key="target.name"
          show-overflow-tooltip :prop="`Employees${target.id}`" :label="target.name">
          <template slot-scope="scope">
            <el-tag v-if="scope.row[`Employees${target.id}`] == 'A'">A</el-tag>
            <el-tag v-if="scope.row[`Employees${target.id}`] == 'B'" type="success">B</el-tag>
            <el-tag v-if="scope.row[`Employees${target.id}`] == 'C'" type="info">C</el-tag>
            <el-popover placement="top" trigger="hover" :content="scope.row[`ReasonE${target.id}`]">
              <el-tag v-if="scope.row[`Employees${target.id}`] == 'D'" slot="reference" type="warning">D</el-tag>
            </el-popover>
            <el-popover placement="top" trigger="hover" :content="scope.row[`ReasonE${target.id}`]">
              <el-tag v-if="scope.row[`Employees${target.id}`] == 'E'" slot="reference" type="danger">E</el-tag>
            </el-popover>
          </template>
        </el-table-column>

        <!-- 表格操作列 -->
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <!-- <el-button size="mini" title="查看" type="primary" @click="handleDetail(scope.row)">
                <i class="fa fa-eye" />
              </el-button>
              <el-button size="mini" title="编辑" type="primary" @click="handleEdit(scope.row)">
                <i class="fa fa-pencil" />
              </el-button> -->
              <el-button size="mini" title="删除" type="danger" @click="handleDel(scope.row)">
                <i class="fa fa-trash-o" />
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页信息 -->
      <div class="pagination-container">
        <el-pagination background layout="total, prev, pager, next, jumper" @current-change="handlePageChange"
          @size-change="handleSizeChange" :current-page="pageNum" :total="tableData.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="mode === 'add' ? '新增' : '编辑'" :visible.sync="showEditDialog" :before-close="handleDialogClose">
      <evaluation-record-edit :mode="mode" ref="editForm" :record="currentRecord" @after-edit="handleAfterEdit" />
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import EvaluationRecordApi from '../api/evaluationRecord'
import evaluationRecordEdit from './evaluationRecordEdit'
import ImportExcel from '@/components/ImportExcel'
import EvaluateEmployeesApi from '../../evaluateEmployees/api/evaluateEmployees'
import EvaluationDepartmentApi from '../../evaluationDepartment/api/evaluationDepartment'
import SysUserApi from '../../user/api/sysUser'
import {parseTime} from "../../../utils/index"
export default {
  name: 'EvaluationRecordList',
  components: {
    evaluationRecordEdit,
    ImportExcel
  },
  data() {
    return {
      /* 搜索请求数据*/
      searchForm: {
        month:parseTime(new Date(),'{y}-{m}')
      },
      pageSize: 10,
      pageNum: 1,
      // 表格数据
      tableData: {
        results: []
      },
      mode: 'edit',
      // 是否显示添加/编辑对话框
      showEditDialog: false,
      // 当前处理行
      currentRecord: {},
      queryLoading: false,
      exportLoading: false,
      autoWidth: true,
      bookType: 'xlsx',
      EmployeesList: [],
      DepartmentList: [],
      users: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 页面初始化
    init() {
      this.handleQuery()
      EvaluateEmployeesApi.queryByCond({}, 100, 1).then(res => {
        if (res.data.code == 200) {
          this.EmployeesList = res.data.data.list
        }
      })
      EvaluationDepartmentApi.queryByCond({}, 100, 1).then(res => {
        if (res.data.code == 200) {
          this.DepartmentList = res.data.data.list
        }
      })
      SysUserApi.queryByCond({}, 1000, 1).then(res => {
        if (res.data.code == 200) {
          this.users = res.data.data.list
        }
      })
    },
    handleQuery() {
      this.pageNum = 1
      this.query()
    },
    handleExportExcel() {
      this.exportLoading = true
      let param = {}

      param = Object.assign({}, this.searchForm)
      EvaluationRecordApi
        .queryByCond(param, 0, 0).then(rspData => {

          let datalist = []
          const data = rspData.data.data.list

          datalist =data.map((item,index) => {
                return {
                  ...item,
                  ...JSON.parse(data[index].deptRecord),
                  ...JSON.parse(data[index].userRecord),
                  ...JSON.parse(data[index].deptSituationRecord),
                  ...JSON.parse(data[index].userSituationRecord)
                }
              })

          import('@/vendor/Export2Excel').then(excel => {
            let tHeader = [
              '评测人',
              '测评时间',
            ]
            tHeader=tHeader.concat(this.DepartmentList.map(item=>item.name))
            tHeader=tHeader.concat(this.EmployeesList.map(item=>item.name))
            let filterVal = [
              'name',
              'createTime',

            ]
            filterVal=filterVal.concat(this.DepartmentList.map(item=>`Department${item.id}`))
            filterVal=filterVal.concat(this.EmployeesList.map(item=>`Employees${item.id}`))
            console.log(filterVal,888)
            const list = datalist
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '导出Excel',
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
            this.exportLoading = false
          })
        }).catch(error => {
          this.exportLoading = false
          //console.log(error)
          if (error.message !== '') {
            //Message.error(error.message)
          }
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    query() {
      return new Promise((resolve, reject) => {
        this.queryLoading = true

        const param = Object.assign({}, this.searchForm)
        EvaluationRecordApi
          .queryByCond(param, this.pageSize, this.pageNum)
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              const data = response.data.data
              data.list = data.list.map((item,index) => {
                return {
                  ...item,
                  ...JSON.parse(data.list[index].deptRecord),
                  ...JSON.parse(data.list[index].userRecord),
                  ...JSON.parse(data.list[index].deptSituationRecord),
                  ...JSON.parse(data.list[index].userSituationRecord)
                }
              })

              this.tableData = data
            } else {
              Message.error(data.message)
              reject()
            }
            this.queryLoading = false
          })
          .catch(error => {
            if (error.message !== '') {
              //Message.error(error.message)
            }
            this.queryLoading = false
            reject(error)
          })
      })
    },
    mockData() {
      setTimeout(() => {
        this.tableData = {
          total: 3, list: [
            {
              'name': '评测人-Data-1',
              'deptRecord': '部门评测记录-Data-1',
              'userRecord': '用户评测记录-Data-1',
            },
            {
              'name': '评测人-Data-2',
              'deptRecord': '部门评测记录-Data-2',
              'userRecord': '用户评测记录-Data-2',
            },
            {
              'name': '评测人-Data-3',
              'deptRecord': '部门评测记录-Data-3',
              'userRecord': '用户评测记录-Data-3',
            },
          ]
        }
      }, 1000)
    },
    handleAdd() {
      this.mode = 'add'
      this.currentRecord = {}
      this.showEditDialog = true
    },
    handleDetail(row) {
      this.mode = 'details'
      this.currentRecord = Object.assign({}, row)
      this.showEditDialog = true
    },
    handleEdit(row) {
      this.mode = 'edit'
      this.currentRecord = Object.assign({}, row)
      this.showEditDialog = true
    },

    // 处理翻页事件
    handlePageChange(currentPage) {
      this.pageNum = currentPage
      this.query()
    },
    // 处理页面总条数事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.query()
    },
    // 处理对话框关闭事件
    handleDialogClose(done) {
      this.$refs.editForm.resetFields()
      done()
    },
    handleDel(row) {
      this.$confirm('确定删除吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const param = Object.assign({}, row)
          EvaluationRecordApi
            .delete(param)
            .then(response => {
              const data = response.data
              if (data.code === 200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.handleQuery()
              } else {
                Message.error(data.message)
              }
            })
            .catch(error => {
              //console.log(error)
              if (error.message !== '') {
                //Message.error(error.message)
              }
            })
        }).catch(() => {
        })
    },
    // 处理编辑对话框关闭事件
    handleAfterEdit() {
      this.showEditDialog = false
      this.$refs.editForm.resetFields()
      this.query()
    }
  }
}
</script>
<style scoped>
.container {
  margin: 10px;
}

.table-container {
  margin-top: 0px;
}

.pagination-container {
  margin-top: 30px;
  text-align: right;
}

.el-tag {
  padding: 8px 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
